/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.home.gui;

import com.google.common.collect.ImmutableSet;
import com.home.common.ApplicationCommon;
import com.home.common.Constants;
import com.home.common.utils.DateUtils;
import com.home.item.ScorecardTypeComboItem;
import com.home.item.WeekComboItem;
import com.home.logic.ScorecardLogic;
import com.home.logic.ScorecardTypeLogic;
import com.home.logic.TeamLogic;
import com.home.logic.VentureLogic;
import com.home.mapping.Agent;
import com.home.mapping.Scorecard;
import com.home.mapping.ScorecardType;
import com.home.mapping.Team;
import com.home.mapping.Venture;
import com.home.model.table.AgentTeamScorecard;
import com.home.model.table.ScorecardTableModel;
import com.home.table.editor.ColorColumnRenderer;
import com.home.table.editor.ColorColumnRendererSCThree;
import java.awt.Color;
import java.awt.Dimension;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.swing.JOptionPane;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import javax.swing.SwingWorker;
import javax.swing.table.DefaultTableModel;
import net.coderazzi.filters.gui.AutoChoices;
import net.coderazzi.filters.gui.TableFilterHeader;

/**
 *
 * @author pnduy
 */
public class QAWorkingList extends javax.swing.JInternalFrame {
    
    private Venture currentVenture = new Venture();
    private MainScreen main;
    private Map<Integer,Agent> mapAgents = new HashMap<>();
    private Agent agentSelected = new Agent();
    private Scorecard scorecardSelected = new Scorecard();
    private Map<Integer,List<Scorecard>> mapScorecard = new HashMap<>();
    List<ScorecardType> listScoreType = new ArrayList<>();
    private boolean isInitted = false;
    /**
     * Creates new form QAScorecardAgent
     */
    public QAWorkingList(MainScreen main) {
        initComponents();
        
        
        
        new TableFilterHeader(tblAgent, AutoChoices.ENABLED);
        new TableFilterHeader(tblScorecard, AutoChoices.ENABLED);
        
        // disable button
        setStatusButton(false);
        
        setSize(new Dimension(main.getWidth() - 5, main.getHeight() - 91));
        this.main = main;
        
        //cboweek.addActionListener(new ItemChane);
        
        // setting value for year
        spinnerYear.setValue(Calendar.getInstance().get(Calendar.YEAR));
        // setting value for week in year        
        int year = Integer.parseInt(spinnerYear.getValue().toString());
        Map<Integer, Date[]> mapWeekInYear = DateUtils.getMapWeekInYear(year);
        SimpleDateFormat formatOnlyYear = new SimpleDateFormat("yyyy");
        for (int week : mapWeekInYear.keySet()) {
            
            Date dateFrom = mapWeekInYear.get(week)[0];                      
            Date dateTo = mapWeekInYear.get(week)[1];
            SimpleDateFormat formatter = new SimpleDateFormat("MMM-dd");
            String labelTime = "";
            if (Integer.parseInt(formatOnlyYear.format(dateTo)) <= year) {
                labelTime = "Week "+week+" "+formatter.format(dateFrom)+" to "+formatter.format(dateTo);
            } else {
                labelTime = "Week "+week+" ("+(year+1)+") "+formatter.format(dateFrom)+" to "+formatter.format(dateTo);
            }
            cboweek.addItem(new WeekComboItem(week, labelTime));
        }
        
        
        // setting data for combo scorecard type
        listScoreType = new ScorecardTypeLogic().findAllScrorecardType();
        ScorecardType allType = new ScorecardType();
        allType.setType("All");
        allType.setIdScorecardType(-1);
        cbScorecardType.addItem(new ScorecardTypeComboItem(allType));
        for (ScorecardType scorecardType : listScoreType) {
            cbScorecardType.addItem(new ScorecardTypeComboItem(scorecardType));
        }               
        isInitted = true;
        currentVenture = main.getAgentLogin().getTeam().getVenture();
        currentVenture.setTeams(ImmutableSet.copyOf(new TeamLogic().findTeamsAndAgentsByVenture(currentVenture.getIdVenture())));
        
        // setting data for week
        setCurrentWeek(DateUtils.getCurrentWeekOfYear());
        
        tblAgent.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        tblScorecard.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jSplitPane1 = new javax.swing.JSplitPane();
        leftPanel = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        spinnerYear = new javax.swing.JSpinner();
        jLabel2 = new javax.swing.JLabel();
        cboweek = new javax.swing.JComboBox();
        jSeparator1 = new javax.swing.JSeparator();
        jLabel3 = new javax.swing.JLabel();
        cbScorecardType = new javax.swing.JComboBox();
        jScrollPane1 = new javax.swing.JScrollPane();
        tblAgent = new javax.swing.JTable();
        rightPanel = new javax.swing.JPanel();
        jPanel1 = new javax.swing.JPanel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        lblAgentName = new javax.swing.JLabel();
        lblVenture = new javax.swing.JLabel();
        lblTeam = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        tblScorecard = new javax.swing.JTable();
        jPanel3 = new javax.swing.JPanel();
        btnAdd = new javax.swing.JButton();
        btnUpdate = new javax.swing.JButton();
        btnDelete = new javax.swing.JButton();
        btnRefresh = new javax.swing.JButton();

        setClosable(true);
        setTitle("QA - Working List");
        setPreferredSize(new java.awt.Dimension(1000, 600));

        jSplitPane1.setDividerLocation(420);

        leftPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("List Agent"));
        leftPanel.setPreferredSize(new java.awt.Dimension(300, 568));

        jLabel1.setText("Year");

        spinnerYear.setEditor(new javax.swing.JSpinner.NumberEditor(spinnerYear, "####"));

        jLabel2.setText("Week");

        cboweek.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                cboweekItemStateChanged(evt);
            }
        });
        cboweek.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cboweekActionPerformed(evt);
            }
        });

        jLabel3.setText("Scorecard Type");

        cbScorecardType.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbScorecardTypeActionPerformed(evt);
            }
        });

        tblAgent.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "idAgent", "Employee Id", "Agent", "Team", "Evaluated Txns"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Integer.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Object.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tblAgent.getTableHeader().setReorderingAllowed(false);
        tblAgent.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                tblAgentMousePressed(evt);
            }
        });
        jScrollPane1.setViewportView(tblAgent);
        if (tblAgent.getColumnModel().getColumnCount() > 0) {
            tblAgent.getColumnModel().getColumn(0).setMinWidth(0);
            tblAgent.getColumnModel().getColumn(0).setPreferredWidth(0);
            tblAgent.getColumnModel().getColumn(0).setMaxWidth(0);
        }

        javax.swing.GroupLayout leftPanelLayout = new javax.swing.GroupLayout(leftPanel);
        leftPanel.setLayout(leftPanelLayout);
        leftPanelLayout.setHorizontalGroup(
            leftPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSeparator1)
            .addGroup(leftPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(leftPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(leftPanelLayout.createSequentialGroup()
                        .addGroup(leftPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, leftPanelLayout.createSequentialGroup()
                                .addComponent(jLabel1)
                                .addGap(18, 18, 18))
                            .addGroup(leftPanelLayout.createSequentialGroup()
                                .addComponent(jLabel2)
                                .addGap(13, 13, 13)))
                        .addGroup(leftPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(spinnerYear)
                            .addComponent(cboweek, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                    .addGroup(leftPanelLayout.createSequentialGroup()
                        .addComponent(jLabel3)
                        .addGap(18, 18, 18)
                        .addComponent(cbScorecardType, 0, 294, Short.MAX_VALUE)))
                .addContainerGap())
            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
        );
        leftPanelLayout.setVerticalGroup(
            leftPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(leftPanelLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(leftPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(spinnerYear, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(leftPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(cboweek, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(leftPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(cbScorecardType, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 451, Short.MAX_VALUE))
        );

        jSplitPane1.setLeftComponent(leftPanel);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Information"));

        jLabel4.setText("Agent Name");

        jLabel5.setText("Venture");

        jLabel6.setText("Team");

        lblAgentName.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        lblAgentName.setText("...");

        lblVenture.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        lblVenture.setText("...");

        lblTeam.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        lblTeam.setText("...");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel4)
                    .addComponent(jLabel5))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(lblVenture)
                        .addGap(144, 144, 144)
                        .addComponent(jLabel6)
                        .addGap(18, 18, 18)
                        .addComponent(lblTeam))
                    .addComponent(lblAgentName))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(6, 6, 6)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(lblAgentName))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(jLabel6)
                    .addComponent(lblVenture)
                    .addComponent(lblTeam))
                .addContainerGap(14, Short.MAX_VALUE))
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("List Scorecard"));

        tblScorecard.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Scorecard", "Scorecard Type", "Evaluation Date", "Transaction Date", "Evaluator", "Score"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.Object.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.String.class, java.lang.Long.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tblScorecard.getTableHeader().setReorderingAllowed(false);
        tblScorecard.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mousePressed(java.awt.event.MouseEvent evt) {
                tblScorecardMousePressed(evt);
            }
        });
        jScrollPane2.setViewportView(tblScorecard);
        if (tblScorecard.getColumnModel().getColumnCount() > 0) {
            tblScorecard.getColumnModel().getColumn(0).setMinWidth(0);
            tblScorecard.getColumnModel().getColumn(0).setPreferredWidth(0);
            tblScorecard.getColumnModel().getColumn(0).setMaxWidth(0);
        }

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Command"));

        btnAdd.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/icon/add.png"))); // NOI18N
        btnAdd.setText("Add New");
        btnAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddActionPerformed(evt);
            }
        });

        btnUpdate.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/icon/edit.png"))); // NOI18N
        btnUpdate.setText("Update");
        btnUpdate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnUpdateActionPerformed(evt);
            }
        });

        btnDelete.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/icon/delete.png"))); // NOI18N
        btnDelete.setText("Delete");
        btnDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDeleteActionPerformed(evt);
            }
        });

        btnRefresh.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/icon/btn_reset.png"))); // NOI18N
        btnRefresh.setText("Refresh");
        btnRefresh.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRefreshActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel3Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(btnRefresh)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnDelete)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnUpdate)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnAdd)
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnAdd)
                    .addComponent(btnUpdate)
                    .addComponent(btnDelete)
                    .addComponent(btnRefresh))
                .addGap(0, 11, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 546, Short.MAX_VALUE)
            .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 388, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel3, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        javax.swing.GroupLayout rightPanelLayout = new javax.swing.GroupLayout(rightPanel);
        rightPanel.setLayout(rightPanelLayout);
        rightPanelLayout.setHorizontalGroup(
            rightPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        rightPanelLayout.setVerticalGroup(
            rightPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(rightPanelLayout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jSplitPane1.setRightComponent(rightPanel);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSplitPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 984, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSplitPane1)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void tblAgentMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblAgentMousePressed
        int r = tblAgent.getSelectedRow();
        if (r < 0) {
            return;
        } else {
            setStatusButton(true);
            Integer id = Integer.parseInt(tblAgent.getValueAt(r, 0).toString());
            agentSelected = mapAgents.get(id);
            loadInfoAgent(agentSelected);
        }
    }//GEN-LAST:event_tblAgentMousePressed

    private void tblScorecardMousePressed(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblScorecardMousePressed
        int r = tblScorecard.getSelectedRow();
        DefaultTableModel model = (DefaultTableModel)tblScorecard.getModel();
        scorecardSelected = (Scorecard)model.getValueAt(r, 0);
        
        if (r < 0) {
            return;
        } else {
            if (evt.getClickCount() == 2) {
                main.addNewInternalFrame(new AgentScorecard(main,scorecardSelected.getScorecardType(), agentSelected, currentVenture, scorecardSelected, mapAgents,this));               
            }
        }


    }//GEN-LAST:event_tblScorecardMousePressed

    private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddActionPerformed
        ScorecardTypeComboItem[] cbItem = new ScorecardTypeComboItem[cbScorecardType.getItemCount()-1];
               
        ScorecardTypeComboItem selected = (ScorecardTypeComboItem)cbScorecardType.getSelectedItem();
        for (int i = 1; i< cbScorecardType.getItemCount();i++) {
            cbItem[i - 1] = (ScorecardTypeComboItem)cbScorecardType.getItemAt(i);                       
        }
        
        main.addNewInternalFrame(new ChooseScorecardTypeDialog(main,cbItem, agentSelected, currentVenture, mapAgents, selected.getValue(), this));
        
    }//GEN-LAST:event_btnAddActionPerformed

    private void cboweekActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cboweekActionPerformed
        if (isInitted) {
            final WaitingDialog loadingDialog = new WaitingDialog(main, true);
            SwingWorker<?, ?> worker = new SwingWorker<Void, Void>() {
                @Override
                protected Void doInBackground() throws Exception {
                    loadDataAgents();
                    return null;
                }

                @Override
                protected void done() {
                    loadingDialog.dispose();
                }
            };
            worker.execute();
            loadingDialog.setVisible(true);
        }
    }//GEN-LAST:event_cboweekActionPerformed

    private void cboweekItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cboweekItemStateChanged
        //loadDataAgents();
    }//GEN-LAST:event_cboweekItemStateChanged

    private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeleteActionPerformed
        int r = tblScorecard.getSelectedRow();
        if (r < 0) {
            JOptionPane.showMessageDialog(main, "Please choose scorecard !");
        } else {
            if (scorecardSelected.getIdScorecard() == null) {
                DefaultTableModel model = (DefaultTableModel) tblScorecard.getModel();
                scorecardSelected = (Scorecard) model.getValueAt(r, 0);
            }
            int rd = JOptionPane.showConfirmDialog(main, "Are you sure ?", "Notify", JOptionPane.OK_CANCEL_OPTION);
            if (rd == JOptionPane.OK_OPTION) {
                final WaitingDialog loadingDialog = new WaitingDialog(main, true);
                SwingWorker<?, ?> worker = new SwingWorker<Void, Void>() {
                    @Override
                    protected Void doInBackground() throws Exception {
                        if (new ScorecardLogic().deteteScorecard(scorecardSelected)) {
                            loadDataAgents();
                            loadInfoAgent(agentSelected);
                            scorecardSelected = new Scorecard();
                            JOptionPane.showMessageDialog(main, "Delete successful !");
                        } else {
                            JOptionPane.showMessageDialog(main, "Delete fail !");
                        }
                        return null;
                    }

                    @Override
                    protected void done() {
                        loadingDialog.dispose();
                    }
                };
                worker.execute();
                loadingDialog.setVisible(true);

            }
        }
    }//GEN-LAST:event_btnDeleteActionPerformed

    private void btnUpdateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnUpdateActionPerformed
        int r = tblScorecard.getSelectedRow();

        if (r < 0) {
            return;
        } else {
            DefaultTableModel model = (DefaultTableModel) tblScorecard.getModel();
            scorecardSelected = (Scorecard) model.getValueAt(r, 0);                       
            main.addNewInternalFrame(new AgentScorecard(main, scorecardSelected.getScorecardType(), agentSelected, currentVenture, scorecardSelected, mapAgents, this));
            
        }
    }//GEN-LAST:event_btnUpdateActionPerformed

    private void btnRefreshActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRefreshActionPerformed
        final WaitingDialog loadingDialog = new WaitingDialog(main, true);
            SwingWorker<?, ?> worker = new SwingWorker<Void, Void>() {
                @Override
                protected Void doInBackground() throws Exception {
                    refreshData();
                    return null;
                }

                @Override
                protected void done() {
                    loadingDialog.dispose();
                }
            };
            worker.execute();
            loadingDialog.setVisible(true);
        
        
    }//GEN-LAST:event_btnRefreshActionPerformed

    private void cbScorecardTypeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbScorecardTypeActionPerformed
        if (isInitted) {
            final WaitingDialog loadingDialog = new WaitingDialog(main, true);
            SwingWorker<?, ?> worker = new SwingWorker<Void, Void>() {
                @Override
                protected Void doInBackground() throws Exception {
                    loadDataAgents();
                    return null;
                }

                @Override
                protected void done() {
                    loadingDialog.dispose();
                }
            };
            worker.execute();
            loadingDialog.setVisible(true);

        }
    }//GEN-LAST:event_cbScorecardTypeActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAdd;
    private javax.swing.JButton btnDelete;
    private javax.swing.JButton btnRefresh;
    private javax.swing.JButton btnUpdate;
    private javax.swing.JComboBox cbScorecardType;
    private javax.swing.JComboBox cboweek;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSplitPane jSplitPane1;
    private javax.swing.JLabel lblAgentName;
    private javax.swing.JLabel lblTeam;
    private javax.swing.JLabel lblVenture;
    private javax.swing.JPanel leftPanel;
    private javax.swing.JPanel rightPanel;
    private javax.swing.JSpinner spinnerYear;
    private javax.swing.JTable tblAgent;
    private javax.swing.JTable tblScorecard;
    // End of variables declaration//GEN-END:variables
    private void loadInfoAgent(Agent agent) {       
        lblAgentName.setText(agent.getAgentName());
        lblVenture.setText(currentVenture.getVentureName());
        lblTeam.setText(agent.getTeam().getTeamName());
                              
        DefaultTableModel modelScorecard = (DefaultTableModel) tblScorecard.getModel();
        modelScorecard.setRowCount(0);      
        List<Scorecard> listScorecard = mapScorecard.get(agent.getIdAgent());
        for (Scorecard sc : listScorecard) {
            
            ScorecardTableModel sm = new ScorecardTableModel();
            sm.setScorecard(sc);         
            sm.setScorecardType(sc.getScorecardType().getType());
            sm.setEvalutationDate(sc.getEvalutationDate());
            sm.setTransactionDate(sc.getTransactionDate());
            sm.setEvaluator(mapAgents.get(sc.getFkAgentEvaluator()).getAgentName());
            sm.setScore(sc.getTotalScore());
            modelScorecard.addRow(sm.toVector());
        }
    }
    
    private ScorecardType getScorecardType() {
        ScorecardTypeComboItem item = (ScorecardTypeComboItem) cbScorecardType.getSelectedItem();
        return item.getValue();
    }
    
    private void loadDataAgents() {
        mapAgents.clear();
        List<AgentTeamScorecard> listData = new ArrayList<AgentTeamScorecard>();
        for (Object obj : currentVenture.getTeams()) {
            
            Team team = (Team) obj;
            
            for (Object objAgent : team.getAgents()) {
                Agent agent = (Agent)objAgent;
                mapAgents.put(agent.getIdAgent(),agent);                
            }
            
        }
        
        //int year = Integer.parseInt(spinnerYear.getValue().toString());
        WeekComboItem weekItem = (WeekComboItem)cboweek.getSelectedItem();
        
        int week = weekItem.getValue();
        
        List<Scorecard> listScorecard = new ScorecardLogic().findScorecardsOfAgentInPeriod(new ArrayList(mapAgents.keySet()), week, getScorecardType().getIdScorecardType());
        
        for (Agent agent : mapAgents.values()) {
            AgentTeamScorecard agentTeamScorecard = new AgentTeamScorecard();
            agentTeamScorecard.setIdAgent(agent.getIdAgent());
            agentTeamScorecard.setAgentName(agent.getAgentName());
            agentTeamScorecard.setTeam(agent.getTeam().getTeamName());
            agentTeamScorecard.setEmployeeId(agent.getEmployeeId());
            int numScorecard = 0;
            List<Scorecard> listSc = new ArrayList<>();
            for (Scorecard scorecard : listScorecard) {
                
                if (scorecard.getAgent().getIdAgent().compareTo(agent.getIdAgent()) == 0) {
                    numScorecard ++;
                    listSc.add(scorecard);
                }
            }
            agentTeamScorecard.setScorecardNo(numScorecard);
            mapScorecard.put(agent.getIdAgent(), listSc);
            listData.add(agentTeamScorecard);
        }
        
        DefaultTableModel model = (DefaultTableModel)tblAgent.getModel();
        model.setRowCount(0);
        for (AgentTeamScorecard obj : listData) {
            model.addRow(obj.toVector());
        }
        
        ColorColumnRendererSCThree columnRenderer = new ColorColumnRendererSCThree(Color.decode("#00a652"), Color.WHITE);
        columnRenderer.setHorizontalAlignment( SwingConstants.CENTER );
        tblAgent.getColumnModel().getColumn(4).setCellRenderer(columnRenderer);
    }
    
    private int getIndexOfVenture(String name) {
        int index = 0;
        List<Venture> listVenture = new VentureLogic().findAllVenture();
        for (int i = 0; i< listVenture.size(); i++) {
            if (listVenture.get(i).getVentureName().equals(name)) {
                index = i;
                break;
            }
        }
        return index;
    }
    
    private int getIndexOfTeam(String name) {
        int index = 0;
        List<Team> listTeam = new TeamLogic().findAllTeam();
        for (int i = 0; i< listTeam.size(); i++) {
            if (listTeam.get(i).getTeamName().equals(name)) {
                index = i;
                break;
            }
        }
        return index;
    }
    
    private void setCurrentWeek(int currentWeek) {
        int index = 0;
        for (int i = 0; i < cboweek.getItemCount(); i++) {
            WeekComboItem item = (WeekComboItem) cboweek.getItemAt(i);
            if (item.getValue() == currentWeek) {
                index = i;
                break;
            }
        }
        cboweek.setSelectedIndex(index);
    }
    
    private void setStatusButton(boolean status) {
        btnAdd.setEnabled(status);
        btnDelete.setEnabled(status);
        btnUpdate.setEnabled(status);
    }
    
    public void refreshData() {
        final int rowSelected = tblAgent.getSelectedRow();
        if (rowSelected < 0) {
            return;
        } else {
            Integer id = Integer.parseInt(tblAgent.getValueAt(rowSelected, 0).toString());
            agentSelected = mapAgents.get(id);
            loadDataAgents();
            loadInfoAgent(agentSelected);
            tblAgent.setRowSelectionInterval(rowSelected, rowSelected);

        }
    }
}
